package com.action;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import com.bean.InstrumentBean;
import com.bean.RecordBean;
import com.dao.InstrumentDao;
import com.dao.ReturnDao;
import com.exception.BackException;
import com.exception.DBException;
import com.exception.InstrumentException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ReturnAction
{
	private void BEAN_JSON_SEND(HttpServletResponse response,
			RecordBean recordBean)
	{
		Gson gson = new GsonBuilder().setDateFormat("MM-dd-yyyy").create();
		String json = gson.toJson(recordBean);
		response.setContentType("application/json");
		try
		{
			Writer w = response.getWriter();
			w.write(json);
			w.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	public void backIns(HttpServletResponse response, RecordBean recordBean)
			throws DBException, InstrumentException, BackException
	{
		InstrumentBean insBean = new InstrumentBean();
		insBean.setBarcode(recordBean.getBarcode());
		InstrumentDao insDao = new InstrumentDao();
		if (!insDao.ifInsExist(insBean))
		{
			throw new InstrumentException("Instrument is not exist!");
		}
		if ("yes".equals(insDao.ifInsBorrowed(insBean)))
		{
			throw new InstrumentException("Instrument is being in room!");
		}

		ReturnDao rd = new ReturnDao();
		rd.backRecord(recordBean);
		rd.getBackResult(recordBean);
		this.prompt(recordBean);
		this.BEAN_JSON_SEND(response, recordBean);
	}
	private void prompt(RecordBean recordBean)
	{
		java.sql.Date sbackdate = recordBean.getSBackDate();
		java.sql.Date backdate = recordBean.getBackDate();
		int result = sbackdate.compareTo(backdate);
		if(result == 0)
		{
			recordBean.setLoan("lucky guy! deadline of loan is today.");
			
		}else if(result > 0)
		{
			recordBean.setLoan("on the tick!");
			
		}else if(result < 0)
		{
			recordBean.setLoan("I hope that you will keep moving ahead!");
		}else
		{
			recordBean.setLoan("well,something is wrong,sorry.");
		}
	}
}